import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user'
import { useCartStore } from './cart'
// 储存用户信息
export const useUserStore = defineStore(
  'user',
  () => {
    // 调用购物车store
    const cartStore = useCartStore()
    // 定义用户管理的state
    const userInfo = ref({})
    // 定义获取数据的action函数
    const getUserInfo = async ({ account, password }) => {
      const res = await loginAPI({ account, password })
      userInfo.value = res.data
      await cartStore.updateCartList()
    }
    const isLogin = computed(() => {
      console.log(userInfo.value)
      return (
        Object.keys(userInfo.value).length > 0 && userInfo.value.data.user.id
      )
    })
    // 退出时清除用户信息
    const clearUserInfo = () => {
      userInfo.value = {}
      cartStore.clearCart()
    }
    return {
      getUserInfo,
      userInfo,
      clearUserInfo,
      isLogin
    }
  },
  {
    persist: true
  }
)
